import {getSession} from '@/libs/sessionStorage'
import {selectHanderWork, selectNotHanderWork} from '@/api/workTask'
import {reactive, toRefs} from 'vue'
import {toScoreBySelf, toSetTarget, toTargetBaseInfo} from '@/libs/pageRedirect'
import useProgress from '@/hooks/pm/progress'
import {useLinkPmStore} from '@/pinia'
import useOwner from '@/hooks/pm/owner'
const {udpateOwnerByPmId} = useOwner()
import {checkIsPhone} from '@/libs/toolkit'
import {to_phone_pmBaseInfo} from '@/libs/pageRedirect'
// import useGlobalAPI from '@/hooks/useGlobalAPI'
// const {router, store, route} = useGlobalAPI()

// const loginUserInfo = computed(() => store.getters['dingding/ddUserInfo'])

/**
 * 代办事项 hook
 */
function useBackLogs() {
  let state = reactive<{
    notHanderWorkList: WorkTask.Task[]
    handerWorkList: WorkTask.Task[]
  }>({
    notHanderWorkList: [],
    handerWorkList: []
  })

  function setNotHanderWorkList(data: WorkTask.Task[]) {
    state.notHanderWorkList = data
  }

  const linkPmStore = useLinkPmStore()
  function updateNotHanderWorkList() {
    const {getProgressById, progressById} = useProgress()
    let userDDId = getSession('userDDId')
    if (!userDDId) return
    selectNotHanderWork({userDDId})
      .then(res => {
        console.log(1235)
        console.log('待办任务', res.data)

        setNotHanderWorkList(res.data)

        res.data.sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime())

        // 获取url携带的pmId
        getGetLinkPmId()

        // url携带的pmId
        let linkPmId = window.localStorage.getItem('linkPmId')

        console.log('当前环境', process.env.NODE_ENV)
        let hrefToUrl = ''
        if (process.env.NODE_ENV == 'development') {
          hrefToUrl = 'http://localhost:8083'
        } else {
          hrefToUrl = 'http://d.lohand.com:8809'
        }
        console.log('hrefToUrl', hrefToUrl)
        console.log(linkPmId, locPmId)

        // isHavePmId
        if (isHavePmId()) {
          console.log('aqsd携带了pmId')
          // window.location.href = hrefToUrl
        } else {
          console.log('aqsd没有携带pmId')
          return
        }

        // if (linkPmId) {
        //   console.log(2)
        //   res.data.forEach(async itemd => {
        //     if (linkPmId == itemd.pmId) {
        //       console.log(3)
        //       console.log('是否可以跳转', linkPmStore.isNaviToLinkPmPage)

        //       // console.log('比对完成', itemd.pmId)
        //       // itemd.isLinkPm = true
        //       let progress = await getProgressById({pmProgressId: itemd.pmProgressId})
        //       console.log(progress)
        //       if (!progress) return

        //       // 是否可以进行跳转(第一次进页面)
        //       if (linkPmStore.isNaviToLinkPmPage) {
        //         console.log(4)
        //         console.log('开始跳转')
        //         setIsNaviToLinkPmPage()

        //         // 判断是移动端还是PC端
        //         if (checkIsPhone()) {
        //           // Phone
        //           console.log('移动端')

        //           udpateOwnerByPmId({
        //             pmId: itemd.pmId,
        //             success(dataR) {
        //               console.log('获取成功', dataR)

        //               to_phone_pmBaseInfo({
        //                 defaultPmId: itemd.pmId,
        //                 userDDId: dataR.pmUserDDId
        //               })
        //             }
        //           })
        //         } else {
        //           // PC
        //           switch (progress.pmProgressStep) {
        //             case 1:
        //               console.log('选择了跳转1')

        //               toSetTarget({
        //                 pmId: itemd.pmId,
        //                 progressId: itemd.pmProgressId
        //               })

        //               break
        //             case 2:
        //               console.log('选择了跳转2')
        //               toTargetBaseInfo({
        //                 defaultPmId: itemd.pmId,
        //                 title: itemd.workTaskContent.replace(
        //                   /\S{2}:([^需要您的确认]{0,})需要您的确认$/,
        //                   '$1'
        //                 ),
        //                 type: 'targetByLeader'
        //               })
        //               break
        //             case 4:
        //               console.log('选择了跳转4')
        //               toScoreBySelf({
        //                 defaultPmId: itemd.pmId
        //               })
        //               break
        //             case 6:
        //             case 7:
        //               console.log('选择了跳转7')
        //               toTargetBaseInfo({
        //                 defaultPmId: itemd.pmId,
        //                 title: itemd.workTaskContent.replace(
        //                   /\S{2}:([^需要您的评分]{0,})需要您的评分$/,
        //                   '$1'
        //                 ),
        //                 type: 'scoreByLeader'
        //               })

        //               break
        //           }
        //         }
        //       }
        //     }
        //   })
        // }

        // console.log('当前url地址', window.location.href)
      })
      .catch(err => {})
  }

  // setIsNaviToLinkPmPage
  function setIsNaviToLinkPmPage() {
    linkPmStore.isNaviToLinkPmPage = false
  }

  function setHanderWorkList(data: WorkTask.Task[]) {
    state.handerWorkList = data
  }
  function updateHanderWorkList() {
    let userDDId = getSession('userDDId')
    if (!userDDId) return
    selectHanderWork({userDDId})
      .then(res => {
        res.data.sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime())
        setHanderWorkList(res.data)
      })
      .catch(err => {})
  }

  function getGetLinkPmId() {
    console.log(location.href, 'window.location.host')
    let pmId

    // 判断是否携带参数
    if (location.href.indexOf('?') != -1 && location.href.indexOf('myPerformance') != -1) {
      let yPList = location.href.split('?')[1].split('&')
      let paramD = {}
      yPList.forEach(param => {
        let psd = param.split('=')
        let keyName = psd[0]
        let keyValue
        if (psd[1].indexOf('/') == -1 && psd[1].indexOf('#') == -1) {
          keyValue = psd[1]
        } else if (psd[1].indexOf('/') != -1) {
          keyValue = psd[1].split('/')[0].slice(0, -1)
        } else if (psd[1].indexOf('#') != -1) {
          keyValue = psd[1].split('#')[0].slice(0, -1)
        }
        paramD[keyName as string] = keyValue
      })
      console.log('截取参数：', paramD)

      // dd.biz.auth
      //   .requestAuthInfo({
      //     authorizeType: '2'
      //   })
      //   .then(res => {
      //     console.log(res, 'rrrrrrr')
      //   })

      // 如果URL中有pmId,那就跳转到link-pm页面，并且存数据
      // if (paramD.pmid) {
      //   pmId = paramD.pmid
      //   console.log('有pmid', pmId)

      //   window.localStorage.setItem('linkPmId', paramD.pmid)

      //   window.history.replaceState({}, document.title, window.location.pathname)
      // }

      if (paramD.pmId) {
        pmId = paramD.pmId
        console.log('有pmId', pmId)

        window.localStorage.setItem('linkPmId', paramD.pmId)
        console.log('#保存pmId')

        window.history.replaceState({}, document.title, window.location.pathname)
      }
    }

    // return pmId
  }

  // 判断有没有携带pmid
  function isHavePmId() {
    let url = window.location.href
    let flag = false
    if (url.indexOf('pmId') != -1 || url.indexOf('pmid') != -1) {
      flag = true
    } else {
      flag = false
    }
    return flag
  }

  return {
    ...toRefs(state),
    updateBackLogs: updateNotHanderWorkList,
    updateHanderWorkList
  }
}

export default useBackLogs
